package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.sms.config.SmsConfiguration;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.leyou.sms.config.SmsConstants.*;

@Slf4j
@Component
public class SmsUtils {

    @Autowired
    private IAcsClient acsClient;

    @Autowired
    private SmsProperties smsProperties;

    public void  SendMessage(String PhoneNumbers, String SignName, String template, String param) {

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain(smsProperties.getDomain());
        request.setVersion(smsProperties.getVersion());
        request.setAction(smsProperties.getAction());
        request.putQueryParameter(SMS_PARAM_REGION_ID, smsProperties.getRegionID());
        request.putQueryParameter(SMS_PARAM_KEY_PHONE, PhoneNumbers);
        request.putQueryParameter(SMS_PARAM_KEY_SIGN_NAME, SignName);
        request.putQueryParameter(SMS_PARAM_KEY_TEMPLATE_CODE, template);
        request.putQueryParameter(SMS_PARAM_KEY_TEMPLATE_PARAM, param);

        try {
            CommonResponse response = acsClient.getCommonResponse(request);
            if (response.getHttpStatus() >= 300){
                log.error("【SMS服务】发送短信失败。响应信息：{}",response.getData());
            }
            System.out.println(response.getData());
        } catch (ServerException e) {
            log.error("【短信服务】发送短信失败，阿里云服务端异常，{}",e.getMessage(),e);
            e.printStackTrace();
        } catch (ClientException e) {
            log.error("【短信服务】发送短信失败，客户端异常，{}",e.getMessage(),e);
            e.printStackTrace();
        }

    }
}
